<?php
namespace app\admin\controller;
use app\model\Bill as BillModel;
use think\Db;


class Bill extends Base
{
    
    public $exception = [];

    public function __construct(){
        $model = new BillModel();
        $this->model = $model;
        parent::__construct();
        
        $page_info = $this->page_info;
        $page_info['title'] = '账单';

        if ( in_array($page_info['action'], ['add','edit']) ) {
           
        }

        $model_dates = getBillDates();
        $this->assign([
            'model'=>$this->model,
            'page_info'=>$page_info,
            'model_dates'=>$model_dates
        ]);
    }

    public function getMap(){
        $map_params = [
            ['key'=>'order_id','type'=>'='],
            ['key'=>'related_order_id','type'=>'='],
            ['key'=>'product_code','type'=>'='],
            ['key'=>'subscription_type','type'=>'='],
            ['key'=>'order_type','type'=>'='],
            ['key'=>'ower_id','type'=>'='],
        ];
        $map = getSearchParam($map_params);
        // if (isSearchParam('start_time') && isSearchParam('end_time')) {
        //     $map[] = ['create_time','between',[strtotime(input('start_time')),strtotime(input('end_time'))]];
        // }else if (isSearchParam('start_time')) {
        //     $map[] = ['create_time','>=',strtotime(input('start_time'))];
        // }else if (isSearchParam('end_time')) {
        //     $map[] = ['create_time','<=',strtotime(input('end_time'))];
        // }
        if (isSearchParam('start_time')) {
            $map[] = ['payment_time','>=',strtotime(input('start_time'))];
        }
        if (isSearchParam('end_time')) {
            $map[] = ['payment_time','<',strtotime(input('end_time'))];
        }
        if (isSearchParam('billing_cycle')) {
            $map[] = ['billing_cycle','like',input('billing_cycle').'%'];
        }

        return $map;
    }

    public function createSearch(){
        $model = $this->model;
        $tmp_products = Db::name('product')->field('code,name')->select();
        $products = [];
        foreach ($tmp_products as $k => $vo) {
            $products[$vo['code']] = $vo['name'].'（'.$vo['code'].'）';
        }
        $search_params = [
            [
                ['key'=>'billing_cycle','name'=>'账期','type'=>'text'],
                ['key'=>'order_id','name'=>'订单号','type'=>'text'],
                ['key'=>'ower_id','name'=>'客户UID','type'=>'text'],
                ['key'=>'order_type','name'=>'订单类型','type'=>'select1_1','params'=>BillModel::getOTypeList()],
                ['key'=>'subscription_type','name'=>'订阅类型','type'=>'select1_1','params'=>BillModel::getSubscriptionTypeList()],
                ['key'=>'start_time','name'=>'开始时间','type'=>'date'],
                ['key'=>'end_time','name'=>'结束时间','type'=>'date'],
                ['key'=>'product_code','name'=>'产品','type'=>'select2_1','params'=>$products],
                ['key'=>'page_size','name'=>'行数','type'=>'text','placeholder'=>'默认20，建议100内'],
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);
    }

    public function index(){
        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $model = $this->model;
        }else{
            $model = Db::name('bill'.$model_date);
        }
        
        // 获取筛选条件
        $map = $this->getMap();
        // 创建搜索
        $this->createSearch();

        $page_param = [
            'page'=>input('page',1),
            'list_rows'=>emptyDef(input('page_size'),20)
        ];
        $list = $model->field('product_type,currency,goods_code,goods_name',true)->where($map)->order('id','desc')->paginate($page_param);
        $page = $list->render();

        $list = $list->toarray();
        $customers = [];
        foreach ($list['data'] as $k => $vo) {
            if (empty($customers[$vo['ower_id']])) {
                $customer = Db::name('user')->field('id,name')->where('pk',$vo['ower_id'])->find();
                $customers[$vo['ower_id']] = $customer;
            }
            $list['data'][$k]['customer'] = $customers[$vo['ower_id']];
            
            $list['data'][$k]['admin_name'] = Db::name('admin')->where('id',$vo['admin_id'])->value('truename');
        }
        return view('index', [
            'list'=>$list,
            'page'=>$page,
        ]);
    }

    public function exportIndex(){
        set_time_limit ( 0 );
        ini_set('memory_limit','20480M');

        // 获取筛选条件
        $map = $this->getMap();
        // 创建搜索
        $this->createSearch();

        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $model = $this->model;
        }else{
            $model = Db::name('bill'.$model_date);
        }

        $total = $model->where($map)->count();
        // $rows = floor($total * 0.2);
        // if ($rows > 1000000) {
        //     $rows = 1000000;
        // }else{
        //     $rows = 500000;
        // }
        $rows = 500000;
        return view('exportIndex', [
            'total'=>$total,
            'rows'=>$rows,
            'nums'=>ceil($total/$rows)
        ]);
    }

    public function export(){
        // echo(date('Y-m-d H:i:s'));
        set_time_limit ( 0 );
        ini_set('memory_limit','40960M');

        $ulogin = $this->login_user;
        // 获取筛选条件
        $map = $this->getMap();

        $num = input('num',0);
        $rows = 500000;

        $model = $this->model;
        $model_date = session('bill_model_date');
        if (empty($model_date)) {
            $model2 = $this->model;
        }else{
            $model2 = Db::name('bill'.$model_date);
        }
        $no_fields = 'product_code,product_type,currency,goods_code,goods_name';
        if ($num > 0) {
            $list = $model2->field($no_fields,true)->limit(($num-1)*$rows,$rows)->where($map)->order('id','asc')->select(); 
        }else{
            $list = $model2->field($no_fields,true)->where($map)->order('id','asc')->select();   
        }
        
        $data = [];
        // $title = ['客户名称','订单号','主账号订单号','客户经理','产品名称','产品类型','订单类型','交易时间','服务开始时间','服务结束时间','创建时间','实例id','实例昵称','实例Tag','资源组','打包售卖ID','打包售卖信息','地域','实例配置','实例规格','公网ip','私网ip','可用区','计费项','服务时长','原价','平台成本','客户主管成本','客户经理成本','客户融合云实付','客户阿里云实付'];
        $title = ['客户名称','订单号','主账号订单号','客户经理','产品名称','订阅类型','订单类型','交易时间','服务开始时间','服务结束时间','创建时间','实例id','实例昵称','实例Tag','资源组','打包售卖ID','打包售卖信息','地域','实例配置','实例规格','公网ip','私网ip','可用区','计费项','服务时长','原价','用户折扣','实付金额'];

        $admins = Db::name('admin')->field('id,truename')->select();
        $admins = arrayParamExtract($admins,'id','truename');

        $users = Db::name('user')->field('pk,name')->select();
        $users = arrayParamExtract($users,'pk','name');        

        $dsn_config = config('config.dsn_config');
        $order_type_sn = $model->getOTypeList();
        foreach ($list as $k => $vo) {
            // if (empty($customers[$vo['ower_id']])) {
            //     // $customer = Db::connect($dsn_config)->table('customer_info')->field('customer_name,user_id')->where('pk',$vo['ower_id'])->find();
            //     // $customer['user_name'] = Db::connect($dsn_config)->table('sys_user')->where('id',$customer['user_id'])->value('user_name');
            //     // $customers[$vo['ower_id']] = $customer;
            //     $customer = Db::name('user')->field('id,truename,admin_id')->where('pk',$vo['ower_id'])->find();
            //     // $customer['admin_name'] = Db::name('admin')->where('id',$customer['admin_id'])->value('truename');
            //     $customers[$vo['ower_id']] = $customer;
            // }
            // if (empty($admins[$vo['ower_id']])) {
            //     $admins[$vo['ower_id']] = Db::name('admin')->where('id',$vo['admin_id'])->value('truename');
            // }
            $tmp = [
                $users[$vo['ower_id']],
                $vo['order_id']."\t",
                $vo['related_order_id']."\t",
                $admins[$vo['admin_id']],
                $vo['product_name'],
                $model->getSubscriptionTypeCn($vo['subscription_type']),
                $model->getOTypeCn($vo['order_type']),
                timeDef($vo['payment_time'],'','Y-m-d H:i:s'),
                $vo['usage_start_time'],
                $vo['usage_end_time'],
                timeDef($vo['create_time']),
                $vo['instance_id'],
                $vo['instance_nick'],
                $vo['tag'],
                $vo['resource_group'],
                $vo['solution_id'],
                $vo['solution_name'],
                $vo['region'],
                $vo['instance_config'],
                $vo['instance_spec'],
                $vo['public_ip'],
                $vo['private_ip'],
                $vo['zone'],
                $vo['fee_item'],
                $vo['service_duration'],
                $vo['pretax_gross_amount'],
                $vo['user_discount'],
                $vo['platform_amount']
                // $vo['trade_original_money'],
                // $vo['trade_mreal_money'],
                // $vo['admin_money'],
                // $vo['user_money'],
                // $vo['customer_money'],
                // $vo['trade_real_money']
            ];
            $data[] = $tmp;
        }
        // dump(count($data));die;
        exportCsv(date('YmdHis'),$title,$data);
        // $file_name = $num . ".csv";
        // $file_path= "C:/csv/"  . $file_name;

        // $data = implode("\r\n", $data);
        // file_put_contents($file_path, $data);
        // echo(date('Y-m-d H:i:s'));
    }

    // 统计
    public function statistics(){
        set_time_limit ( 0 );
        ini_set('memory_limit','10240M');

        // $dsn_config = config('config.dsn_config');
        // $customers = Db::connect($dsn_config)->table('customer_flow_detail')->field('trade_time,income_money,expend_money,balance_money,create_time')->where([
        //     ['customer_id','=','6f2a0ee2d4c94af29b46098b4f43c5d1'],
        //     ['income_money','>',0]
        // ])->select();

        // $title = ['交易时间','收入金额','支出金额','余额','创建时间'];
        // $data = [];
        // $data[] = implode(',', $title);
        // foreach ($customers as $k => $vo) {
        //     $tmp = [
        //         $vo['trade_time'],
        //         $vo['income_money'],
        //         $vo['expend_money'],
        //         $vo['balance_money'],
        //         $vo['create_time']
        //     ];
        //     $data[] = implode(',', $tmp);
        // }

        // $file_path= "./bat/abc123456.csv";
        // $data = implode("\r\n", $data);
        // file_put_contents($file_path, $data);
        // exit();

        $model_date = session('bill_model_date');
        // if (empty($model_date)) {
        //     $model = $this->model;
        // }else{
        //     $model = Db::name('bill'.$model_date);
        // }
        
        $map_params = [
            ['key'=>'pk','type'=>'=']
        ];
        $map = getSearchParam($map_params);

        $map_params = [
            ['key'=>'order_id','type'=>'=']
        ];
        $o_map = getSearchParam($map_params);
        if (isSearchParam('start_time')) {
            $o_map[] = ['payment_time','>=',strtotime(input('start_time'))];
        }
        if (isSearchParam('end_time')) {
            $o_map[] = ['payment_time','<=',strtotime(input('end_time'))];
        }

        $dsn_config = config('config.dsn_config');
        $customers = Db::connect($dsn_config)->table('customer_info')->field('pk,customer_name')->select();
        $customers  = arrayParamExtract($customers ,'pk','customer_name');
        $search_params = [
            [
                ['key'=>'pk','name'=>'顾客','type'=>'select2_1','params'=>$customers],
                ['key'=>'order_id','name'=>'订单号','type'=>'text'],
                ['key'=>'start_time','name'=>'开始时间','type'=>'datetime'],
                ['key'=>'end_time','name'=>'结束时间','type'=>'datetime']
            ]
        ];
        $this->assign([
            'search_params'=>$search_params
        ]);

        $list = Db::connect($dsn_config)->table('customer_info')->field('pk,customer_name,balance_money')->where($map)
        ->join('account_info ai','ai.customer_id = customer_info.id','left')
        ->select();
        foreach ($list as $k => $vo) {
            // if ($k > 100) {
            //     break;
            // }
            if (empty($vo['balance_money'])) {
                $list[$k]['balance_money'] = 0;
            }

            $o_map2 = $o_map;
            $o_map2[] = ['ower_id','=',$vo['pk']];
            $statistics = Db::name('bill'.$model_date)->field('sum(platform_amount) as platform_amount,sum(pretax_amount) as pretax_amount,sum(pretax_gross_amount) as pretax_gross_amount')->where($o_map2)->find();
            $list[$k]['pretax_gross_amount'] = emptyDef($statistics['pretax_gross_amount'],0);
            $list[$k]['pretax_amount'] = emptyDef($statistics['pretax_amount'],0);
            $list[$k]['platform_amount'] = emptyDef($statistics['platform_amount'],0);
        }

        return view('statistics', [
            'list'=>$list
        ]);
    }

    public function selDates(){
        $model_dates = getBillDates();
        return view('selDates', [
            'list'=>$model_dates
        ]);
    }

    public function selDate($key='',$page='index'){
        if (empty($key)) {
            $key = null;
        }
        session('bill_model_date',$key);
        return redirect(url($page));
    }



   
}
